package com.coin.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.coin.domain.*;
import com.coin.mapper.UserFavoriteMarketMapper;
import com.coin.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Auther: 李 力
 * @Date: 2025/6/23
 * @Description: com.coin.service.impl
 * @version: 1.0
 */
@Service
public class UserFavoriteMarketServiceImpl extends ServiceImpl<UserFavoriteMarketMapper, UserFavoriteMarket> implements UserFavoriteMarketService {

    @Autowired
    private MarketService marketService;

    @Autowired
    private Snowflake snowflake;

    /**
     * @Description: 用户收藏某个市场
     * @Author: 李 力
     * @Date: 2025/6/23
     * @Param:
     * @return: R
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveMarket(Long userId, Market market) {
        if (userId == null || market == null) {
            throw new RuntimeException("参数为空");
        }
        UserFavoriteMarket userFavoriteMarket = new UserFavoriteMarket();
        String symbol = market.getSymbol();
        Market marketDb = marketService.getMarkerBySymbol(symbol);
        userFavoriteMarket.setId(snowflake.nextId());
        userFavoriteMarket.setUserId(userId);
        userFavoriteMarket.setMarketId(marketDb.getId());
        userFavoriteMarket.setType(market.getType().intValue());
        return save(userFavoriteMarket);
    }

    /**
     * @Description: 用户取消收藏某个市场
     * @Author: 李 力
     * @Date: 2025/6/23
     * @Param:
     * @return: R
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteUserFavoriteMarket(String symbol, Long userId) {
        if (StrUtil.isEmpty(symbol) || userId == null) {
            throw new RuntimeException("必要参数为空");
        }
        Market market = marketService.getMarkerBySymbol(symbol);
        if (market == null) {
            throw new RuntimeException("交易市场不存在");
        }
        LambdaQueryWrapper<UserFavoriteMarket> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper = queryWrapper.eq(UserFavoriteMarket::getMarketId, market.getId())
                .eq(UserFavoriteMarket::getUserId, userId);
        return remove(queryWrapper);
    }
}

